#include "imPrimitives.h"

/*

Grid geometry primitive
Generates a grid/plane of size WxL, with a spacing between the vertices of S
The object will be oriented facing directly up upon creation (Vector 0,1,0)
The first vertex will be located at 0, 0
All subsequent vertices will extend positively across the X and Z axis
NOTE: Consider different behaviors for this, enabling developers to specify a 'mid point'

The size describes the vertices along each axis. The minimum size to enforce is 2x2 (1 quad)
As such, the number of vertices will be W x L. Meanwhile, the number of quads will be (W-1) x (L-1)
Each quad will contain 2 polys

*/

Grid::Grid(void) {
	SetSize(2, 2);
	SetSpacing(1.0f);
	Build();
};
Grid::Grid(float Space, uint W, uint L) {
	SetSize(W, L);
	SetSpacing(Space);
	Build();
};

void Grid::SetSpacing(float S) {
	if(S <= 0.0f)
		return;
	Spacing = S;
};

void Grid::SetSize(uint W, uint L) {
	Width = max(W, 2);
	Length = max(L, 2);
};

void Grid::Build(void) {
	NumVertices = Width * Length;
	NumFaces = (Width - 1) * (Length - 1) * 2;

	uint NumIndices = NumFaces * 3;

	Vertices = new Vertex[NumVertices];
	Indices = new WORD[NumIndices];

	//
	// Vertices
	//
	for(uint i = 0; i < Width; i++) {
		for(uint j = 0; j < Length; j++) {
			uint VertexIndex = (i * Width) + j;

			Vertex &v = Vertices[VertexIndex];

			v.Pos = Vector3(i * Spacing, 0.0f, j * Spacing);
			v.Normal = Vector3(0.0f, 1.0f, 0.0f);
			v.UV = Vector2((float)i, 1.0f - (float)j);
			for each(char a in v.BoneInds)
				a = 0;

			for each(float a in v.BoneWeights)
				a = 0.0f;

			v.BoneWeights[0] = 1.0f;
		};
	};

	//
	// Indices
	//
	int VerticalBump = Width;

	for(uint y = 0; y < Length - 1; y++) {
		for(uint x = 0; x < Width - 1; x++) {
			//
			// One per quad
			//
			uint i = ((y * (Width - 1)) + x) * 6; // First index of this quad
			uint bl = (y * Width) + x; // Bottom-left vertex of this quad

			Indices[i + 0] = bl;
			Indices[i + 1] = bl+VerticalBump+1;
			Indices[i + 2] = bl+VerticalBump;

			Indices[i + 3] = bl+VerticalBump+1;
			Indices[i + 4] = bl;
			Indices[i + 5] = bl+1;
		}
	};

	return;
};